package com.example.test001.service.impl;

import com.example.test001.dao.*;
import com.example.test001.model.SysMenu;
import com.example.test001.model.User;
import com.example.test001.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class IUserService implements UserService {


    @Autowired
    UserMapper userMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    RolePermissionMapper rolePermissionMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Autowired
    SysMenuMapper sysMenuMapper;

    @Override
    public User selectUserByUID(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public User UserLogin(String username) {
        return userMapper.selectByUserName(username);
    }

    @Override
    public Set<String> getRoleById(Integer id) {
        return userRoleMapper.selectUserRolesByUid(id);
    }

    @Override
    public List<SysMenu> getPermissionById(Integer id) {
        return rolePermissionMapper.selectUserPermissionByUid(id);
    }




    public List<SysMenu> getMenus(){
        List<SysMenu> sysMenus = sysMenuMapper.getAll();
        List<SysMenu> firstMenus = new ArrayList<>();

        for (SysMenu items :sysMenus) {

            if(items.getParentId().equals(0)){
                firstMenus.add(items);
            }

        }


        for (SysMenu s:firstMenus) {
            s= getChild(s,sysMenus);
        }

        return firstMenus;

    }


    private  SysMenu getChild(SysMenu parent,List<SysMenu> sysMenus){

        List<SysMenu> child = new ArrayList<>();
        for (SysMenu sysMenu: sysMenus) {
            if(sysMenu.getParentId().equals(parent.getMenuId())){
                getChild(sysMenu,sysMenus);
                child.add(sysMenu);
                parent.setSysMenus(child);
            }

        }
        return parent;

    }


}
